package com.cat.binaryTree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/vertical-order-traversal-of-a-binary-tree/description/?envType=problem-list-v2&envId=stfxhiIc
 * @create 2025/9/20 16:42
 * @since JDK17
 */

public class Solution55 {
    List<int[]> list = new ArrayList<>();
    void dfs(TreeNode root, int row , int col) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            dfs(root.left, row + 1,col - 1);
        }
        if (root.right != null) {
            dfs(root.right, row + 1,col + 1);
        }
    }

    public List<List<Integer>> verticalTraversal(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        dfs(root, 0, 0);
        list.sort((a, b) -> {
            if (a[1] != b[1]) {
                return a[1] - b[1];
            }
            if (a[0] != b[0]) {
                return a[0] - b[0];
            }
            return a[2] - b[2];
        });
        int last = Integer.MIN_VALUE;
        List<Integer> cur = null;
        for (int[] x : list) {
            if (x[1] != last) {
                last = x[1];
                cur = new ArrayList<>(List.of(x[2]));
                ans.add(cur);
            } else {
                cur.add(x[2]);
            }
        }

        return ans;
    }
}
